package com.alibaba.moco;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.moco.monitor.ScriptClassLoader;
import com.alibaba.moco.util.BaseTypeUtil;

import groovy.lang.GroovyObject;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import net.sf.json.JSONObject;


/**
 * 脚本执行类
 * 
 * @author wb-lj240895
 *
 */
public class MocoScriptRunner {
	private static final Logger logger = LoggerFactory.getLogger(MocoScriptRunner.class);

	/**
	 * 更改脚本加载方式 解决脚本重复加载问题
	 * @param request
	 * @param scriptName
	 * @return
	 * @throws IOException
	 * @throws ResourceException
	 * @throws ScriptException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static Object excuteScriptCache(HttpServletRequest request, String scriptName)
			throws IOException, ResourceException, ScriptException, IllegalAccessException, InstantiationException {
		if (!StringUtils.isBlank(scriptName) && scriptName.startsWith("script/")) {
			scriptName = scriptName.replace("script/", "");
		} else if (!StringUtils.isBlank(scriptName) && scriptName.startsWith("/")) {
			scriptName = scriptName.substring(1);
		}

		GroovyObject scriptInstance = ScriptClassLoader.getScriptObject(scriptName + ".groovy");
		if (scriptInstance != null) {
			Object res = scriptInstance.invokeMethod("excute", request);
			return res;
		} else {
			logger.info("脚本不存在：{}", scriptName);
			return null;
		}
	}

	/**
	 * 
	 * @param request
	 * @param scriptName
	 * @return
	 */
	public static Object excuteScript(HttpServletRequest request, String scriptName)
			throws IOException, ResourceException, ScriptException, IllegalAccessException, InstantiationException {
		// System.out.println(BaseTypeUtil.getClassPath());
		GroovyScriptEngine engine = new GroovyScriptEngine(BaseTypeUtil.getClassPath());
		Class<?> scriptClass = engine.loadScriptByName(scriptName + ".groovy");

		GroovyObject scriptInstance = (GroovyObject) scriptClass.newInstance();
		Object res = scriptInstance.invokeMethod("excute", request);
		return res;

	}

	/**
	 * 返回静态的json数据
	 * 
	 * @param jsonName
	 * @return
	 * @throws IOException
	 */
	public static Object excuteJson(String jsonName) throws IOException {
		File filename = new File(BaseTypeUtil.getClassPath() + jsonName + ".json"); // 要读取以上路径的input。txt文件
		InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一个输入流对象reader
		@SuppressWarnings("resource")
		BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
		StringBuilder jsonBuilder = new StringBuilder();

		String line = br.readLine();
		while (line != null) {
			jsonBuilder.append(line);
			line = br.readLine();

		}
		// System.out.println(jsonBuilder.toString());
		return JSONObject.fromObject(jsonBuilder.toString());

	}
}
